import axios from "axios";
import store from "@/store";
import { Message } from "element-ui";
import router from "@/router";

const instance = axios.create({
  baseURL: "/video",
  timeout: 10000,
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    if (config.isExcel) {
      config.responseType = "blob";
    }
    if (!config.url.includes("login")) {
      config.data.token = store.state.user.token;
    }
    return config;
  },
  (err) => Promise.reject(err)
);

// 响应拦截器
instance.interceptors.response.use(
  (res) => {
    if (res.config.isExcel) {
      if (res.data) {
        return res;
      } else {
        Message.error("服务异常");
        return Promise.reject(res);
      }
    }

    if (res.data.sts === "0") {
      return res.data;
    } else if (res.data.sts === "-1000") {
      router.push("/login");
    } else if (res.data.sts === "2") {
      return res.data;
    } else if (res.config.url.includes("getNewOrganList")) {
      return res.data;
    }
    //
    Message.warning(res.data.msg || "服务异常");
    // return res.data;
    return Promise.reject(res.data);
  },
  (err) => {
    if (err.status?.status === "1") {
      // 跳转到login页面重新登录
      router.push("/login");
    }

    // 错误的默认情况 => 只要给提示
    Message.error(err.response.data.message || "服务异常");
    return Promise.reject(err);
  }
);

export default instance;
